#include <bits/stdc++.h>
using namespace std;
#define int long long
void solve()
{
    int a,b;
    cin>>a>>b;
    int tb=b,cb=0;
    while(tb)
    {
        if(tb&1)cb++;
        tb>>=1;
    }
    if (cb==0) 
    {
        if(a==1)cout<<-1<<endl;
        else if(a%2==0)cout<<a<<endl;
        else cout<<a+3<<endl;
    }
    else if(b==1)
    {
        if(a%2==0)cout<<a+3<<endl;
        else cout<<a<<endl;
    }
    else 
    {
        if(cb==1)
        {
            if(a%2)cout<<b+a-1<<endl;
            else cout<<a+b<<endl;
        }
        else 
        {
            cout<<b+max(0ll,(a-cb)%2?a-cb+1:a-cb)<<endl;
        }
    }
}
signed main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(nullptr);
    int T=1;
    cin>>T;
    while(T--)
    {
       solve();
    }
    return 0;
}